<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown转图片/视频工具</title>
    <script src="/static/js/marked.min.js"></script>
    <script src="/static/js/html2canvas.min.js"></script>
    <script src="/static/js/chroma.min.js"></script>
    <style>
        /* 定义字体 */
        @font-face {
            font-family: 'Arial';
            src: local('Arial');
        }
        @font-face {
            font-family: 'Microsoft YaHei';
            src: url('/static/fonts/msyh.ttc');
        }
        @font-face {
            font-family: 'SimSun';
            src: url('/static/fonts/simsun.ttc');
        }
        @font-face {
            font-family: 'KaiTi';
            src: url('/static/fonts/simkai.ttf');
        }
        @font-face {
            font-family: 'FangSong';
            src: url('/static/fonts/simfang.ttf');
        }
        @font-face {
            font-family: 'SimHei';
            src: url('/static/fonts/SIMHEI.TTF');
        }
        @font-face {
            font-family: 'Times New Roman';
            src: url('/static/fonts/times.ttf');
        }

        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .input-section, .output-section {
            flex: 1;
        }
        textarea {
            width: 100%;
            height: 300px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .preview {
            /* border: 1px solid #ddd; */
            padding: 48px;
            width: 960px;
            height: 1280px;
            background-color: #000000;
            box-sizing: border-box;
            margin: 0 auto;
            transform: scale(0.5);
            transform-origin: top left;
        }
        .preview-container {
            width: 480px;
            height: 640px;
            overflow-y: auto;
            overflow-x: hidden;
            margin: 0 auto;
            background-color: #000000;
        }

        #preview.preview {
            background-color: inherit;
            position: relative;
        }

        .preview * {
            background-color: transparent;
        }
        .exported-images {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .exported-image {
            width: 200px;
            cursor: pointer;
            position: relative;
        }
        .exported-image img {
            width: 100%;
            border: 1px solid #ddd;
        }
        .clear-images {
    
            padding: 8px 16px;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            height: 40px;
            font-size: 14px;
            line-height: 24px;
        }
        .clear-images:hover {
            background: #d32f2f;
        }
        .image-actions {
            margin-top: 15px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .generate-video {
            background: #2196F3;
            padding: 8px 16px;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            height: 40px;
            font-size: 14px;
            line-height: 24px;
        }
        .generate-video:hover {
            background: #0b7dda;
        }
        .controls {
            margin: 20px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .color-preset {
            display: inline-block;
            width: 20px;
            height: 20px;
            margin-left: 5px;
            border: 1px solid #ddd;
            cursor: pointer;
        }
        .color-preset:hover {
            transform: scale(1.1);
            box-shadow: 0 0 5px rgba(0,0,0,0.3);
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .style-controls {
            margin-top: 20px;
            padding: 15px;
            background-color: #f5f5f5;
            border-radius: 4px;
        }
        .style-controls label {
            display: block;
            margin: 5px 0;
        }
        .font-controls {
            margin-top: 20px;
            padding: 15px;
            background-color: #f5f5f5;
            border-radius: 4px;
        }
        .font-controls label {
            display: block;
            margin: 10px 0;
        }
        .font-controls input[type="range"] {
            width: 200px;
            margin-right: 10px;
        }

        /* 引用段落样式 */
        blockquote {
            border-left: 4px solid #888888;
            background-color: rgba(255, 255, 255, 0.1);
            margin: 10px 0;
            padding: 10px 20px;
            border-radius: 0 4px 4px 0;
        }
    </style>
</head>
<body>
    <h1>Markdown转图片/视频工具</h1>
    <div class="container">
        <div class="input-section">
            <h3>输入Markdown内容（用***分隔多张图片）</h3>
            <textarea id="markdown-input" placeholder="输入Markdown内容..."></textarea>
            
            <div>
                <button id="export-btn" style="margin-top: 16px;">导出图片</button>
                
                
                
            </div>
            
            <div class="style-controls">
                <h3>样式设置</h3>
                <div style="margin-top: 14px; display: flex;">
                    <label for="preset-select">预设样式 </label>
                    <select id="preset-select" style="margin-left: 36px; ">
                        <option value="">自定义</option>
                    </select>
                </div>
                <div style="margin: 10px 0;display:flex;">
                    <label><input type="radio" name="bg-type" value="color" checked> 背景颜色</label>
                    <label style="margin-left: 20px;"><input type="radio" name="bg-type" value="image"> 背景图片（建议3:4，640*854分辨率以上）</label>
                </div>
                <div id="bg-color-controls" class="controls">    
                    <label for="bg-color">背景颜色</label>                
                    <input type="color" id="bg-color" value="#000000" style="margin-left: 32px;">                    
                    <span class="color-preset" style="background:#000000" data-color="#000000" title="黑色"></span>
                    <span class="color-preset" style="background:#293931" data-color="#293931" title="墨绿"></span>
                    <span class="color-preset" style="background:#383329" data-color="#383329" title="深褐"></span>
                </div>
                <div id="bg-image-controls" style="display: none;">
                    <input type="file" id="bg-image-input" accept=".jpg,.jpeg,.png" style="display: none;">
                    <button id="upload-bg-btn" style="margin-top: 10px;">上传背景图片</button>
                    <select id="bg-select" style="margin-top: 10px; margin-left: 10px; display: none;">
                        <option value="">选择已有背景图片</option>
                    </select>
                </div>

                <label>
                    基础文字颜色 
                    <input type="color" id="text-color" value="#ffffff" style="margin-left: 6px;">                    
                </label>
                <label>
                    一级标题颜色 
                    <input type="color" id="h1-color" value="#EFF226" style="margin-left: 6px;">                    
                </label>
                <label>
                    二级标题颜色 
                    <input type="color" id="h2-color" value="#F3F59E" style="margin-left: 6px;">                    
                </label>
                <label>
                    其他标题颜色 
                    <input type="color" id="other-heading-color" value="#FDFFD1" style="margin-left: 6px;">                    
                </label>
                <label>
                    加粗文字颜色 
                    <input type="color" id="bold-color" value="#EFF226" style="margin-left: 6px;">                    
                </label>
                <label>
                    斜体文字颜色 
                    <input type="color" id="italic-color" value="#E01A1A" style="margin-left: 6px;">                    
                </label>
    
            </div>

                <div class="font-controls">
                    <h3>字体设置</h3>
                    <div style="margin-bottom: 15px;">
                        <label for="font-family">选择字体: </label>
                        <select id="font-family" style="margin-left: 10px;">
                            <option value="Arial">Arial</option>
                            <option value="Microsoft YaHei">微软雅黑</option>
                            <option value="SimSun">宋体</option>
                            <option value="KaiTi">楷体</option>
                            <option value="FangSong">仿宋</option>
                            <option value="SimHei">黑体</option>
                            <option value="Times New Roman">Times New Roman</option>
                        </select>
                    </div>
                    <h3>文字大小设置</h3>
                <label>
                    基础字体大小 (18-58px):
                    <input type="range" id="base-font" min="18" max="58" value="30" step="1">
                    <span id="base-font-value">30px</span>
                </label>
                <label>
                    一级标题放大比例 (100-200%):
                    <input type="range" id="h1-scale" min="100" max="200" value="190" step="5">
                    <span id="h1-scale-value">190%</span>
                </label>
                <label>
                    二级标题放大比例 (100-200%):
                    <input type="range" id="h2-scale" min="100" max="200" value="160" step="5">
                    <span id="h2-scale-value">160%</span>
                </label>
                <label>
                    其他标题放大比例 (100-200%):
                    <input type="range" id="other-heading-scale" min="100" max="200" value="110" step="5">
                    <span id="other-heading-scale-value">110%</span>
                </label>
                <label>
                    行间距 (1.0-2.5倍):
                    <input type="range" id="line-height" min="10" max="25" value="16" step="1">
                    <span id="line-height-value">1.6倍</span>
                </label>

            </div>
        </div>
        
        <div class="output-section">
            <h3>预览</h3>
            <div class="preview-container">
                <div id="preview" class="preview"></div>
            </div>
            <h3 id="generated-images-title" style="display:none;margin-top:20px;">以下为生成的图片</h3>
            <div class="exported-images" id="exported-images"></div>
            <div class="music-style" style="margin-top:16px;">
                <label>视频音乐类型:</label>
                <p><label><input type="radio" name="music_style" value="modern" checked> 现代</label>
                <label><input type="radio" name="music_style" value="traditional"> 传统</label>
                </p>
                <p>
                <label><input type="radio" name="music_style" value="custom"> 自己上传音乐<span style="font-size: 12px;">（可上传MP3或MP4格式，如果为MP4格式，则自动提取音频。）</span></label>
                </p>
            </div>
            <div id="custom-music-controls" style="display:none; margin-top:10px;">
                <input type="file" id="music-file" accept=".mp3,.mp4" style="display:none">
                <button id="upload-music-btn">选择音乐文件</button>
                <span id="selected-music-name"></span>
            </div>
        <div class="time-per-pic" style="margin-top:16px;display:none">
            <label>
                每张图片时间 (3-8秒):
                <input type="range" id="time-per-pic" min="3" max="8" value="4" step="1">
                <span id="time-per-pic-value">4秒</span>
            </label>
        </div>
            <div class="image-actions">
                <button class="clear-images" id="clear-images">清除所有图片</button>
                <button class="generate-video" id="generate-video" style="display:none">将图片转为视频</button>
                <span id="generating-text" style="display:none;margin-left:10px;color:#ca0b0b;">正在生成视频...</span>
            </div>
        </div>
    </div>

    <script>
        // 预设样式
        let stylePresets = {};
        
        // 加载预设样式
        async function loadPresets() {
            try {
                const response = await fetch('/static/config/preset_styles.json');
                const data = await response.json();
                stylePresets = {};
                data.presets.forEach(preset => {
                    stylePresets[preset.name] = preset;
                });
            } catch (error) {
                console.error('加载预设样式失败:', error);
            }
        }
        
        // 应用预设样式
        function applyPreset(presetName) {
            const preset = stylePresets[presetName];
            if (!preset) return;
            
            bgColorInput.value = preset.bgColor;
            textColorInput.value = preset.textColor;
            h1ColorInput.value = preset.h1Color;
            h2ColorInput.value = preset.h2Color;
            otherHeadingColorInput.value = preset.otherHeadingColor;
            boldColorInput.value = preset.boldColor;
            italicColorInput.value = preset.italicColor;
            baseFontInput.value = preset.baseFont;
            h1ScaleInput.value = preset.h1Scale * 100;
            h2ScaleInput.value = preset.h2Scale * 100;
            otherHeadingScaleInput.value = preset.otherHeadingScale * 100;
            
            // 设置行间距（如果预设中有定义，否则使用默认值16）
            if (preset.lineHeight !== undefined) {
                lineHeightInput.value = preset.lineHeight * 10;
            } else {
                lineHeightInput.value = 16; // 默认值1.6倍
            }
            
            // 更新显示值
            baseFontValue.textContent = `${preset.baseFont}px`;
            h1ScaleValue.textContent = `${preset.h1Scale * 100}%`;
            h2ScaleValue.textContent = `${preset.h2Scale * 100}%`;
            otherHeadingScaleValue.textContent = `${preset.otherHeadingScale * 100}%`;
            lineHeightValue.textContent = `${(lineHeightInput.value / 10).toFixed(1)}倍`;
            
            // 更新currentStyles对象
            currentStyles.textColor = preset.textColor;
            currentStyles.h1Color = preset.h1Color;
            currentStyles.h2Color = preset.h2Color;
            currentStyles.otherHeadingColor = preset.otherHeadingColor;
            currentStyles.boldColor = preset.boldColor;
            currentStyles.italicColor = preset.italicColor;
            currentStyles.baseFont = preset.baseFont;
            currentStyles.h1Scale = preset.h1Scale;
            currentStyles.h2Scale = preset.h2Scale;
            currentStyles.otherHeadingScale = preset.otherHeadingScale;

            updateStyles();
            updateFontSizes();
            updateLineHeight();
            updateBackgroundColor();
            
            // 强制重新渲染
            if (markdownInput.value) {
                const currentContent = preview.innerHTML;
                preview.innerHTML = currentContent;
                applyStyles();
            }
        }

        // 初始化样式
        let currentStyles = {
            textColor: '#ffffff',
            h1Color: '#EFF226',
            h2Color: '#F3F59E',
            otherHeadingColor: '#FDFFD1',
            boldColor: '#EFF226',
            italicColor: '#E01A1A',
            underlineColor: '#ffffff',
            baseFont: 30,
            h1Scale: 1.9,
            h2Scale: 1.6,
            otherHeadingScale: 1.1,
            codeScale: 0.9,
            fontFamily: 'Arial'
        };

        // 存储当前背景图片URL
        let currentBgImageUrl = null;

        // 获取DOM元素
        const markdownInput = document.getElementById('markdown-input');
        const preview = document.getElementById('preview');
        const exportBtn = document.getElementById('export-btn');
        const bgColorInput = document.getElementById('bg-color');
        const textColorInput = document.getElementById('text-color');
        const h1ColorInput = document.getElementById('h1-color');
        const h2ColorInput = document.getElementById('h2-color');
        const otherHeadingColorInput = document.getElementById('other-heading-color');
        const boldColorInput = document.getElementById('bold-color');
        const italicColorInput = document.getElementById('italic-color');
        const underlineColorInput = document.getElementById('underline-color');
        const baseFontInput = document.getElementById('base-font');
        const h1ScaleInput = document.getElementById('h1-scale');
        const h2ScaleInput = document.getElementById('h2-scale');
        const otherHeadingScaleInput = document.getElementById('other-heading-scale');
        const codeScaleInput = document.getElementById('code-scale');
        const lineHeightInput = document.getElementById('line-height');
        const lineHeightValue = document.getElementById('line-height-value');
        const baseFontValue = document.getElementById('base-font-value');
        const h1ScaleValue = document.getElementById('h1-scale-value');
        const h2ScaleValue = document.getElementById('h2-scale-value');
        const otherHeadingScaleValue = document.getElementById('other-heading-scale-value');
        const codeScaleValue = document.getElementById('code-scale-value');

        // 初始化滑块显示
        baseFontValue.textContent = `${baseFontInput.value}px`;
        baseFontInput.value = 30; // 设置默认值
        h1ScaleValue.textContent = `${h1ScaleInput.value}%`;
        h2ScaleValue.textContent = `${h2ScaleInput.value}%`;
        otherHeadingScaleValue.textContent = `${otherHeadingScaleInput.value}%`;
        
        // 初始化行间距显示
        lineHeightValue.textContent = `${(lineHeightInput.value / 10).toFixed(1)}倍`;
        lineHeightInput.addEventListener('input', updateLineHeight);
        
        // 初始化每张图片时间滑块
        const timePerPicInput = document.getElementById('time-per-pic');
        const timePerPicValue = document.getElementById('time-per-pic-value');
        timePerPicValue.textContent = `${timePerPicInput.value}秒`;
        timePerPicInput.addEventListener('input', () => {
            timePerPicValue.textContent = `${timePerPicInput.value}秒`;
        });
 

        // 监听预设选择变化
        document.getElementById('preset-select').addEventListener('change', (e) => {
            if (e.target.value) {
                applyPreset(e.target.value);
            }
        });

        // 动态加载预设选项
        async function loadPresetOptions() {
            try {
                const response = await fetch('/static/config/preset_styles.json');
                const data = await response.json();
                const presetSelect = document.getElementById('preset-select');
                
                // 清空现有选项（保留"自定义"选项）
                while (presetSelect.options.length > 1) {
                    presetSelect.remove(1);
                }
                
                // 添加从JSON加载的选项
                data.presets.forEach(preset => {
                    const option = document.createElement('option');
                    option.value = preset.name;
                    option.textContent = preset.name;
                    presetSelect.appendChild(option);
                });
                
                // 设置默认选中"黑色经典"
                presetSelect.value = '黑色经典';
                return data.presets;
            } catch (error) {
                console.error('加载预设选项失败:', error);
                return [];
            }
        }

        // 加载预设并初始化
        loadPresets().then(() => {
            loadPresetOptions().then(() => {
                // 监听输入变化
                markdownInput.addEventListener('input', updatePreview);
                
                // 加载背景图片列表
                loadBackgroundImages();
            });
            
            // 监听样式变化自动切换到自定义
            const styleInputs = [
                textColorInput, h1ColorInput, h2ColorInput, otherHeadingColorInput,
                boldColorInput, italicColorInput, baseFontInput,
                h1ScaleInput, h2ScaleInput, otherHeadingScaleInput,
                lineHeightInput
            ];
            
            styleInputs.forEach(input => {
                input.addEventListener('input', () => {
                    if (document.getElementById('preset-select').value !== '') {
                        document.getElementById('preset-select').value = '';
                    }
                });
            });
        });

        // 加载背景图片列表
        async function loadBackgroundImages() {
            try {
                const response = await fetch('/get_ddstudy_bg_list');
                const data = await response.json();
                
                // console.log('背景图片数据:', data); // 先console.log查看后端返回的数据
                
                if (data.res === 'ok') {
                    buildBackgroundSelect(data.data);
                } else {
                    console.error('获取背景图片列表失败');
                }
            } catch (error) {
                console.error('加载背景图片列表失败:', error);
            }
        }

        // 构建背景图片选择框
        function buildBackgroundSelect(bgData) {
            const bgSelect = document.getElementById('bg-select');
            
            // 清空现有选项（保留默认选项）
            while (bgSelect.options.length > 1) {
                bgSelect.remove(1);
            }
            
            // 添加分类和图片选项
            for (const [category, images] of Object.entries(bgData)) {
                if (images.length > 0) {
                    // 添加分类分组
                    const group = document.createElement('optgroup');
                    group.label = category;
                    
                    // 添加该分类下的所有图片选项
                    images.forEach(imagePath => {
                        const option = document.createElement('option');
                        const fileName = imagePath.split(/[/\\]/).pop(); // 获取文件名
                        // 将本地文件路径转换为服务器可访问的URL
                        const imageUrl = `/serve_bg_image?path=${encodeURIComponent(imagePath)}`;
                        option.value = imageUrl;
                        option.textContent = fileName;
                        group.appendChild(option);
                    });
                    
                    bgSelect.appendChild(group);
                }
            }
            
            // 显示选择框
            bgSelect.style.display = 'inline-block';
            
            // 添加选择事件监听
            bgSelect.addEventListener('change', function() {
                if (this.value) {
                    // 设置当前背景图片URL
                    currentBgImageUrl = this.value;
                    updateBackgroundColor(currentBgImageUrl);
                }
            });
        }

        // 监听样式变化并立即更新预览
        textColorInput.addEventListener('input', updateStyles);
        h1ColorInput.addEventListener('input', updateStyles);
        h2ColorInput.addEventListener('input', updateStyles);
        otherHeadingColorInput.addEventListener('input', updateStyles);
        boldColorInput.addEventListener('input', updateStyles);
        italicColorInput.addEventListener('input', updateStyles);
        baseFontInput.addEventListener('input', updateFontSizes);
        h1ScaleInput.addEventListener('input', updateFontSizes);
        h2ScaleInput.addEventListener('input', updateFontSizes);
        otherHeadingScaleInput.addEventListener('input', updateFontSizes);
        
        // 监听字体变化并更新预览
        document.getElementById('font-family').addEventListener('change', updateFontFamily);

        // 强制重新渲染
        function forceRerender() {
            const markdown = markdownInput.value;
            preview.innerHTML = marked.parse(markdown);
            applyStyles();
        }
        // 添加预设颜色点击事件
        document.querySelectorAll('.color-preset').forEach(preset => {
            preset.addEventListener('click', () => {
                bgColorInput.value = preset.dataset.color;
                updateBackgroundColor();
            });
        });

        // 获取新增的DOM元素
        const bgTypeRadios = document.querySelectorAll('input[name="bg-type"]');
        const bgColorControls = document.getElementById('bg-color-controls');
        const bgImageControls = document.getElementById('bg-image-controls');
        const bgImageInput = document.getElementById('bg-image-input');
        const uploadBgBtn = document.getElementById('upload-bg-btn');
        
        // 背景类型切换事件
        bgTypeRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'color') {
                    bgColorControls.style.display = 'flex';
                    bgImageControls.style.display = 'none';
                } else {
                    bgColorControls.style.display = 'none';
                    bgImageControls.style.display = 'block';
                }
                updateBackgroundColor();
            });
        });

        // 上传背景图片按钮点击事件
        uploadBgBtn.addEventListener('click', function() {
            bgImageInput.click();
        });

        // 背景图片选择事件
        bgImageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    currentBgImageUrl = event.target.result;
                    updateBackgroundColor(currentBgImageUrl);
                }
                reader.readAsDataURL(e.target.files[0]);
            }
        });

        bgColorInput.addEventListener('input', updateBackgroundColor);

        // 更新背景颜色/图片
        function updateBackgroundColor(bgImageUrl) {
            const previewContainer = document.querySelector('.preview-container');
            const preview = document.getElementById('preview');
            
            if (document.querySelector('input[name="bg-type"]:checked').value === 'color') {
                const bgColor = bgColorInput.value;
                previewContainer.style.backgroundImage = 'none';
                previewContainer.style.backgroundColor = bgColor;
                preview.style.backgroundImage = 'none';
                preview.style.backgroundColor = bgColor;
            } else {
                const imageUrl = bgImageUrl || currentBgImageUrl;
                if (imageUrl) {
                    previewContainer.style.backgroundColor = 'transparent';
                    previewContainer.style.backgroundImage = `url(${imageUrl})`;
                    previewContainer.style.backgroundSize = 'cover';
                    preview.style.backgroundColor = 'transparent';
                    preview.style.backgroundImage = `url(${imageUrl})`;
                    preview.style.backgroundSize = 'cover';
                }
            }
        }

        // 更新字体大小
        function updateFontSizes() {
            const baseFont = parseInt(baseFontInput.value);
            const h1Scale = parseInt(h1ScaleInput.value) / 100;
            const h2Scale = parseInt(h2ScaleInput.value) / 100;
            const otherHeadingScale = parseInt(otherHeadingScaleInput.value) / 100;
            
            // 确保值有效
            if (!isNaN(baseFont) && baseFont >= 18 && baseFont <= 58) {
                currentStyles.baseFont = baseFont;
                baseFontValue.textContent = `${baseFont}px`;
            }
            
            if (!isNaN(h1Scale) && h1Scale >= 1 && h1Scale <= 2) {
                currentStyles.h1Scale = h1Scale;
                h1ScaleValue.textContent = `${Math.round(h1Scale * 100)}%`;
            }

            if (!isNaN(h2Scale) && h2Scale >= 1 && h2Scale <= 2) {
                currentStyles.h2Scale = h2Scale;
                h2ScaleValue.textContent = `${Math.round(h2Scale * 100)}%`;
            }

            if (!isNaN(otherHeadingScale) && otherHeadingScale >= 1 && otherHeadingScale <= 2) {
                currentStyles.otherHeadingScale = otherHeadingScale;
                otherHeadingScaleValue.textContent = `${Math.round(otherHeadingScale * 100)}%`;
            }
            
            // 强制重新渲染
            const currentContent = preview.innerHTML;
            preview.innerHTML = currentContent;
            applyStyles();
        }

        // 更新行间距
        function updateLineHeight() {
            const lineHeight = lineHeightInput.value / 10;
            lineHeightValue.textContent = `${lineHeight.toFixed(1)}倍`;
            preview.style.lineHeight = lineHeight;
            
            // 直接应用样式，不需要重新渲染内容
            applyStyles();
        }

        // 导出按钮点击事件
        exportBtn.addEventListener('click', exportToImages);

        // 更新预览
        function updatePreview() {
            const markdown = markdownInput.value;
            preview.innerHTML = marked.parse(markdown);
            applyStyles();
        }

        // 更新字体
        function updateFontFamily() {
            const fontFamily = document.getElementById('font-family').value;
            currentStyles.fontFamily = fontFamily;
            preview.style.fontFamily = fontFamily;
            
            // 强制重新渲染当前内容
            const currentContent = preview.innerHTML;
            preview.innerHTML = '';
            setTimeout(() => {
                preview.innerHTML = currentContent;
                applyStyles();
            }, 0);
        }

        // 更新样式
        function updateStyles() {
            // 更新样式设置
            currentStyles.textColor = textColorInput.value;
            currentStyles.h1Color = h1ColorInput.value;
            currentStyles.h2Color = h2ColorInput.value;
            currentStyles.otherHeadingColor = otherHeadingColorInput.value;
            currentStyles.boldColor = boldColorInput.value;
            currentStyles.italicColor = italicColorInput.value;
            
            // 强制重新渲染当前内容
            const currentContent = preview.innerHTML;
            preview.innerHTML = '';
            setTimeout(() => {
                preview.innerHTML = currentContent;
                applyStyles();
            }, 0);
        }

        // 应用样式
        function applyStyles() {
            // 保存当前内容
            const currentContent = preview.innerHTML;
            
            // 强制重新渲染内容
            preview.innerHTML = currentContent;
            
            // 基础字体样式
            preview.style.fontSize = `${currentStyles.baseFont}px`;
            preview.style.fontFamily = currentStyles.fontFamily;
            preview.style.color = currentStyles.textColor;
            
            // 标题样式
            const h1s = preview.querySelectorAll('h1');
            h1s.forEach(h => {
                h.style.color = currentStyles.h1Color;
                h.style.fontSize = `${1 + 5 * 0.1 * currentStyles.h1Scale}em`;
            });

            const h2s = preview.querySelectorAll('h2');
            h2s.forEach(h => {
                h.style.color = currentStyles.h2Color;
                h.style.fontSize = `${1 + 4 * 0.1 * currentStyles.h2Scale}em`;
            });

            const otherHeadings = preview.querySelectorAll('h3, h4, h5, h6');
            otherHeadings.forEach((h, index) => {
                h.style.color = currentStyles.otherHeadingColor;
                const scale = 1 + (6 - index - 2) * 0.1 * currentStyles.otherHeadingScale;
                h.style.fontSize = `${scale}em`;
            });

            // 加粗样式
            const boldElements = preview.querySelectorAll('strong, b');
            boldElements.forEach(el => {
                el.style.color = currentStyles.boldColor;
            });

            // 斜体样式
            const italicElements = preview.querySelectorAll('em, i');
            italicElements.forEach(el => {
                el.style.color = currentStyles.italicColor;
            });

            // 下划线样式
            const underlineElements = preview.querySelectorAll('u');
            underlineElements.forEach(el => {
                el.style.color = currentStyles.underlineColor;
            });

            // 引用样式
            const blockquotes = preview.querySelectorAll('blockquote');
            blockquotes.forEach(blockquote => {
                blockquote.style.borderLeft = '4px solid #888888';
                blockquote.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
                blockquote.style.margin = '10px 0';
                blockquote.style.padding = '10px 20px';
                blockquote.style.borderRadius = '0 4px 4px 0';
            });
        }

        // 获取导出图片容器和按钮
        const exportedImagesContainer = document.getElementById('exported-images');
        const clearImagesBtn = document.getElementById('clear-images');
        const generateVideoBtn = document.getElementById('generate-video');

        // 清除所有图片
        clearImagesBtn.addEventListener('click', () => {
            exportedImagesContainer.innerHTML = '';
            generateVideoBtn.style.display = 'none';
        });

        // 获取标题元素
        const generatedImagesTitle = document.getElementById('generated-images-title');

        // 监听图片容器变化
            const observer = new MutationObserver(() => {
                const hasImages = exportedImagesContainer.children.length > 0;
                generateVideoBtn.style.display = hasImages ? 'block' : 'none';
                generatedImagesTitle.style.display = hasImages ? 'block' : 'none';
                document.querySelector('.music-style').style.display = hasImages ? 'block' : 'none';
                document.querySelector('.time-per-pic').style.display = hasImages ? 'block' : 'none';
            });
            
            // 初始隐藏音乐类型选择和时间控制
            document.querySelector('.music-style').style.display = 'none';
            document.querySelector('.time-per-pic').style.display = 'none';
        observer.observe(exportedImagesContainer, { childList: true });

        // 自定义音乐上传逻辑
        const musicStyleRadios = document.querySelectorAll('input[name="music_style"]');
        const customMusicControls = document.getElementById('custom-music-controls');
        const musicFileInput = document.getElementById('music-file');
        const uploadMusicBtn = document.getElementById('upload-music-btn');
        const selectedMusicName = document.getElementById('selected-music-name');

        // 监听音乐类型变化
        musicStyleRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                customMusicControls.style.display = this.value === 'custom' ? 'block' : 'none';
            });
        });

        // 上传音乐按钮点击事件
        uploadMusicBtn.addEventListener('click', function() {
            musicFileInput.click();
        });

        // 音乐文件选择事件
        musicFileInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const file = e.target.files[0];
                // 验证文件类型
                if (!file.type.match('audio/mp3') && !file.type.match('audio/mp4') && 
                    !file.name.toLowerCase().endsWith('.mp3') && !file.name.toLowerCase().endsWith('.mp4')) {
                    alert('请选择MP3或MP4格式的音乐文件');
                    musicFileInput.value = '';
                    selectedMusicName.textContent = '';
                    return;
                }
                selectedMusicName.textContent = file.name;
                selectedMusicName.style.marginLeft = '10px';
            }
        });

        // 获取音乐文件数据
        function getMusicFileData() {
            if (document.querySelector('input[name="music_style"]:checked').value === 'custom' && 
                musicFileInput.files && musicFileInput.files[0]) {
                return new Promise((resolve) => {
                    const file = musicFileInput.files[0];
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        const content = e.target.result.split(',')[1]; // 获取base64内容部分
                        resolve({
                            name: file.name,
                            type: file.type,
                            size: file.size,
                            content: content // 添加base64编码的文件内容
                        });
                    };
                    
                    reader.readAsDataURL(file); // 读取为DataURL
                });
            }
            return Promise.resolve(null);
        }

        // 导出为图片
        async function exportToImages() {
            const markdown = markdownInput.value;
            const sections = markdown.split('***');
            const bgColor = bgColorInput.value;
            
            // 先清空之前的图片
            exportedImagesContainer.innerHTML = '';
            
            const bgType = document.querySelector('input[name="bg-type"]:checked').value;
            
            for (let i = 0; i < sections.length; i++) {
                if (sections[i].trim() === '') continue;
                
                // 创建临时预览容器
                const tempPreview = document.createElement('div');
                tempPreview.className = 'preview';
                tempPreview.style.width = '960px';
                tempPreview.style.height = '1280px';
                tempPreview.style.padding = '48px';
                tempPreview.style.boxSizing = 'border-box';
                tempPreview.style.color = textColorInput.value;
                
                if (bgType === 'color') {
                    tempPreview.style.backgroundColor = bgColorInput.value;
                } else if (currentBgImageUrl) {
                    tempPreview.style.backgroundImage = `url(${currentBgImageUrl})`;
                    tempPreview.style.backgroundSize = 'cover';
                }
                
                tempPreview.innerHTML = marked.parse(sections[i]);
                
                // 应用样式到临时预览
                document.body.appendChild(tempPreview);
                applyStylesToElement(tempPreview);
                
                // 确保样式应用完成
                await new Promise(resolve => setTimeout(resolve, 100));
                
                // 转换为图片
                const canvas = await html2canvas(tempPreview, {
                    scale: 2,
                    logging: true,
                    useCORS: true,
                    backgroundColor: null
                });
                
                // 创建图片展示元素
                const imageContainer = document.createElement('div');
                imageContainer.className = 'exported-image';
                
                const img = document.createElement('img');
                img.src = canvas.toDataURL('image/png');
                img.alt = `Markdown图片 ${i+1}`;
                
                imageContainer.appendChild(img);
                exportedImagesContainer.appendChild(imageContainer);
                
                // 移除临时预览
                document.body.removeChild(tempPreview);
            }
            
            // 显示生成视频按钮
            if (sections.length > 0 && sections[0].trim() !== '') {
                generateVideoBtn.style.display = 'block';
            }
        }

        // 获取生成中文本元素
        const generatingText = document.getElementById('generating-text');

        // 生成视频按钮点击事件
        generateVideoBtn.addEventListener('click', async () => {
            const images = Array.from(exportedImagesContainer.querySelectorAll('img')).map(img => img.src);
            
            try {
                // 显示"正在生成"文本
                generatingText.style.display = 'inline';
                generateVideoBtn.disabled = true;
                
                // 获取音乐文件数据（异步）
                const musicData = await getMusicFileData();
                // console.log('调试信息 - 音乐文件数据:', {
                //     hasData: !!musicData,
                //     name: musicData?.name || '无',
                //     type: musicData?.type || '无',
                //     size: musicData?.size || 0,
                //     contentLength: musicData?.content?.length || 0
                // });
                
                const requestData = {
                    images: images,
                    resolution: '960x1280',
                    music_style: document.querySelector('input[name="music_style"]:checked').value,
                    music_file_data: musicData, // 使用获取到的完整数据
                    time_per_pic: document.getElementById('time-per-pic').value
                };
                
                // 调试日志
                console.log('音乐文件数据:', {
                    hasData: !!musicData,
                    name: musicData?.name || '无',
                    size: musicData?.size || 0
                });
                // console.log('调试信息 - 发送给后端的数据:', {
                //     imageCount: images.length,
                //     musicStyle: requestData.music_style,
                //     hasMusicData: !!requestData.music_file_data,
                //     timePerPic: requestData.time_per_pic
                // });

                const response = await fetch('/md_pic_to_video', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    // 获取视频blob数据
                    const blob = await response.blob();
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'markdown_video.mp4';
                    document.body.appendChild(a);
                    a.click();
                    // 清理
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } else {
                    throw new Error('视频生成失败');
                }
            } catch (error) {
                console.error('生成视频出错:', error);
                alert('生成视频时出错: ' + error.message);
            } finally {
                // 隐藏"正在生成"文本
                generatingText.style.display = 'none';
                generateVideoBtn.disabled = false;
            }
        });

        // 为元素应用样式
        function applyStylesToElement(element) {
            // 基础字体样式
            element.style.fontSize = `${currentStyles.baseFont}px`;
            element.style.fontFamily = currentStyles.fontFamily;
            element.style.lineHeight = lineHeightInput.value / 10; // 应用行间距
            
            // 标题样式
            const h1s = element.querySelectorAll('h1');
            h1s.forEach(h => {
                h.style.color = currentStyles.h1Color;
                h.style.margin = '20px 0 10px 0';
                h.style.fontSize = `${1 + 5 * 0.1 * currentStyles.h1Scale}em`;
            });

            const h2s = element.querySelectorAll('h2');
            h2s.forEach(h => {
                h.style.color = currentStyles.h2Color;
                h.style.margin = '20px 0 10px 0';
                h.style.fontSize = `${1 + 4 * 0.1 * currentStyles.h2Scale}em`;
            });

            const otherHeadings = element.querySelectorAll('h3, h4, h5, h6');
            otherHeadings.forEach((h, index) => {
                h.style.color = currentStyles.otherHeadingColor;
                h.style.margin = '20px 0 10px 0';
                const scale = 1 + (6 - index - 2) * 0.1 * currentStyles.otherHeadingScale;
                h.style.fontSize = `${scale}em`;
            });

            // 加粗样式
            const boldElements = element.querySelectorAll('strong, b');
            boldElements.forEach(el => {
                el.style.color = currentStyles.boldColor;
            });

            // 斜体样式
            const italicElements = element.querySelectorAll('em, i');
            italicElements.forEach(el => {
                el.style.color = currentStyles.italicColor;
                el.style.fontStyle = 'italic';
            });

            // 链接样式
            const links = element.querySelectorAll('a');
            links.forEach(link => {
                link.style.color = currentStyles.linkColor;
            });

            // 代码块样式
            const codeBlocks = element.querySelectorAll('pre code');
            codeBlocks.forEach(code => {
                code.style.backgroundColor = currentStyles.codeBg;
                code.style.padding = '10px';
                code.style.borderRadius = '4px';
                code.style.display = 'block';
                code.style.overflowX = 'auto';
                code.style.fontFamily = 'monospace';
                code.style.fontSize = `${currentStyles.codeScale * 100}%`;
            });

            // 段落样式
            const paragraphs = element.querySelectorAll('p');
            paragraphs.forEach(p => {
                p.style.margin = '10px 0';
                p.style.lineHeight = lineHeightInput.value / 10; // 应用行间距到段落
            });

            // 引用样式
            const blockquotes = element.querySelectorAll('blockquote');
            blockquotes.forEach(blockquote => {
                blockquote.style.borderLeft = '4px solid #888888';
                blockquote.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
                blockquote.style.margin = '10px 0';
                blockquote.style.padding = '10px 20px';
                blockquote.style.borderRadius = '0 4px 4px 0';
            });
        }
    </script>
</body>
</html>
